# This is a sample Python script.

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.

import cv2
import numpy as np


# 固定尺寸
# 将图像转为固定高度的图片（这一步是为了适配边缘检测的阈值，下面会介绍）
def resize_img(image, height=900):
    h, w = image.shape[:2]
    pro = height / h
    size = (int(w * pro), int(height))
    img = cv2.resize(image, size)
    return img


# 边缘检测
def get_canny(image):
    # 高斯模糊
    binary = cv2.GaussianBlur(image, (3, 3), 2, 2)
    # 边缘检测
    binary = cv2.Canny(binary, 20, 60, apertureSize=3, L2gradient=True)
    # 膨胀操作，尽量使边缘闭合
    kernel = np.ones((3, 3), np.uint8)
    binary = cv2.dilate(binary, kernel, iterations=1)
    return binary


# 求出面积最大的轮廓
def find_max_contour(image):
    ret, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
    # 边缘
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # 计算面积
    max_area = 0.0
    max_contour = []
    for contour in contours:
        #     currentArea = cv2.contourArea(contour)
        #     # if currentArea > max_area:
        #     if 500 < currentArea < 1000:
        #         max_area = currentArea
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        max_contour.append(contour)
    return contours


# 多边形拟合凸包的四个顶点
def get_box_point(contour):
    # 多边形拟合凸包
    hull = cv2.convexHull(contour)
    epsilon = 0.02 * cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(hull, epsilon, True)
    approx = approx.reshape((len(approx), 2))
    return approx


path = '/Users/wanggh/Desktop/a.jpeg'
outpath = '/Users/wanggh/Desktop/out.jpeg'
img = cv2.imread(path)
img = resize_img(img)
print('shape =', img.shape)
binary_img = get_canny(img)
max_contour = find_max_contour(binary_img)
cv2.drawContours(img, max_contour, -1, (0, 0, 255), 3)
# boxes = getBoxPoint(max_contour)
# for box in boxes:
#     cv2.circle(img, tuple(box), 5, (0, 0, 255), 2)
# print(boxes)
cv2.imwrite(outpath, img)
